package com.wrb.pwd.component;

import com.wrb.pwd.config.RePackageThread;

import javax.swing.*;
import java.awt.*;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

/**
 * @author wrb
 * @date 2019/9/17 13:58
 */
public class MainCardLayout extends JFrame {

	/**
	 * 列表panel
	 */
	private UserListPanel userListPanel = UserListPanel.getInstance();

	private UserRecordPanel userRecordPanel = UserRecordPanel.getInstance();

	private PasswordUpdatePanel passwordUpdatePanel = PasswordUpdatePanel.getInstance();

	private MainCardLayout() {
		super("首页");
		//卡片式布局的面板
		JPanel cards = new JPanel(new CardLayout());
		JButton jbRecord = new JButton("记录用户");
		JButton jbList = new JButton("用户列表");
		JButton jbHome = new JButton("首页");
		JButton jbUpdatePassword = new JButton("修改密码");
		JPanel homePanel = new JPanel();
		homePanel.add(jbRecord);
		homePanel.add(jbList);
		homePanel.add(jbUpdatePassword);

		cards.add(homePanel, "home");
		cards.add(userRecordPanel, "record");
		cards.add(userListPanel, "list");
		cards.add(passwordUpdatePanel, "passwordUpdate");

		CardLayout cl = (CardLayout) (cards.getLayout());
		//调用show()方法显示面板2
		cl.show(cards, "home");
		this.add(cards);
		this.setSize(500, 520);
//		this.setLocation(200, 100);
		this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		//居中显示
		setLocationRelativeTo(cards);
		this.setVisible(true);
		//设置窗口大小不可更改
		this.setResizable(false);

		jbHome.addActionListener(e -> {
			this.setTitle("首页");
			cl.show(cards, "home");
		});
		jbRecord.addActionListener(e -> {
			this.setTitle("记录用户信息");
			userRecordPanel.init();
			userRecordPanel.setHomeButton(jbHome);
			cl.show(cards, "record");
		});
		jbList.addActionListener(e -> {
			this.setTitle("用户列表页");
			userListPanel.init();
			userListPanel.initTable(jbHome, null);
			cl.show(cards, "list");
		});
		jbUpdatePassword.addActionListener(e->{
			//输入密码进入
			PasswordCheckDialog dialog = new PasswordCheckDialog( null);
			int state = dialog.getReturnStatus();
			if (state == 0) {
				dialog.dispose();
				return;
			}
			passwordUpdatePanel.init();
			passwordUpdatePanel.setHomeButton(jbHome);
			cl.show(cards, "passwordUpdate");
		});

		//关闭窗口事件:执行打包操作
		addWindowListener(new WindowAdapter() {
			@Override
			public void windowClosing(WindowEvent e) {
				new RePackageThread();
			}
		});
	}

	public static MainCardLayout getInstance() {
		return Inner.INSTANCE;
	}

	private static class Inner {
		private static final MainCardLayout INSTANCE = new MainCardLayout();
	}


}
